<?php

namespace app\services;

class Book51Service
{

    function getKey()
    {
        return ['FTjTX$2r', 'ZUHLM'];
    }

    private function create_guid()
    {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));

        $hyphen = chr(45);
        $uuid = substr($charid, 6, 2) . substr($charid, 4, 2) .
            substr($charid, 2, 2) . substr($charid, 0, 2) . $hyphen
            . substr($charid, 10, 2) . substr($charid, 8, 2) . $hyphen
            . substr($charid, 14, 2) . substr($charid, 12, 2) . $hyphen
            . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
        return $uuid;

    }

    function getJG_51book($dpt, $arr, $flightNum, $qfrq)
    {
        $time = time();
        $uuid = $this->create_guid();
        $airline = preg_replace('/\d/', '', $flightNum);
        $param = json_encode([
            "rsIsGzip" => true,
            "rqIdentification" => $uuid,
            "timeStamp" => $time . '000',
            "rqData" => [
                "routeType" => "OW",
                "airline" => $airline,
                "segments" => [
                    [
                        "departureTime" => $qfrq,
                        "departureAirport" => $dpt,
                        "arrivalAirport" => $arr
                    ]
                ],
                "passengerType" => 1,
                "needPnr" => 0
            ],
            "thirdUsername" => $this->getKey()[1]
        ]);

//print_r($param);

        $SIGN = md5($param . $this->getKey()[0]);

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://api.51book.com/' . $this->getKey()[1] . '/51/search/Flight/json',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $param,
            CURLOPT_HTTPHEADER => array(
                'USERNAME: ' . $this->getKey()[1],
                'SIGN: ' . $SIGN,
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);

//  print_r($response);
        curl_close($curl);
        $resultArr = json_decode($response, true);

        if (empty($resultArr['rsData']))  return null;
        foreach ($resultArr['rsData'] as $flightArr ){

            if ($flightArr['flightNo'] == $flightNum){
                return $flightArr;
            }
        }
        return null;
    }
}